﻿using System;
using System.Linq;
using System.Xml;

namespace FakeSmsService
{
    public class SmsService : ISmsService
    {
        //List<XmlElement> messages;
        private static int i = 0;
        public XmlElement QuerySMSState(string MessageID)
        {
            if (MessageID.Length == 24 && MessageID.Substring(23, 1) == "9")
            {
                if (i % 3 == 0)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(MakeOutXml("DELIVRD"));
                    return doc.DocumentElement;
                }
                else if (i % 3 == 1)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(MakeOutXml(""));
                    return doc.DocumentElement;
                }
                else
                {
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(MakeOutXml("FAIL"));
                    return doc.DocumentElement;
                }
            }
            else
                return null;
        }

        private string MakeOutXml(string Status)
        {
            i = i % 3 + 1;
            string xmlstring1 = "<?xml version='1.0' encoding='utf-8' ?><NewDataSet><result><mobile>13912345678</mobile><scheduleDate>2010年03月01日 10:21:15</scheduleDate><deliverstate>";
            string xmlstring2 = "</deliverstate><deliverdonetime>2010年03月01日 10:21:45</deliverdonetime></result></NewDataSet>";
            return xmlstring1 + Status + xmlstring2;
        }

        public string SendSMS(string mobile, int FormatID, string Content, DateTime ScheduleDate, string TokenID)
        {
            try
            {
                string[] mobiles = { "139", "138", "137", "136", "135", "134", "159", "158", "157", "157", "187", "188" };
                
                if (String.IsNullOrEmpty(TokenID) || TokenID.Length != 16)
                    return "ERROR:100:[不正确的Token]";
                if (String.IsNullOrEmpty(Content))
                    return "ERROR:103:[短信内容不能为空]";
                if (mobile.Length != 11 || !mobiles.Contains(mobile.Substring(0, 3)))
                    return "ERROR:200:[非手机号]";

                return "OK:[" + TokenID + mobile.Substring(mobile.Length - 7) + "9]";
            }
            catch
            {
                return "ERROR:999:[系统错误]";
            }
            
        }
    }
}
